#include "Animation.h"
#include "Sprite.h"
#include "Utils.h"
#include "TimeController.h"
#include "time.h"
#include "Texture.h"

Animation::Animation()
{
	id = 0;
	nextSpriteDelay = 0.0f;
	isStatic = false;
}

Animation::Animation(int id)
{
	this->id = id;
	nextSpriteDelay = 0.0f;
	isStatic = false;
}

void Animation::AddSprite(Sprite* sprite)
{
	sprites.push_back(sprite);
	curSprite = 0;
}

void Animation::RemoveSprite(int index)
{
	int ii = 0;
	int spritesSize = sprites.size();
	for(int i = 0; i < spritesSize; i++)
	{
		if(ii==index)
		{
			sprites.erase(sprites.begin() + i);
			break;
		}
	}
	curSprite = 0;
}

bool Animation::Update()
{
	bool isFinish = false;

	if(isStatic == true) return isFinish;
	float t = TimeController::GetInstance()->GetDtInSecond();
	nextSpriteDelay+=t;

	float curRenderTime = sprites[curSprite]->GetRenderTime();
	if(nextSpriteDelay>curRenderTime)
	{
		curSprite++;
		if(curSprite == sprites.size())
		{
			isFinish = true;
			curSprite=0;
		}
		nextSpriteDelay-=curRenderTime;
	}

	return isFinish;
}

void Animation::SetSpriteIndex(bool isStatic, int index)
{
	this->isStatic = isStatic;
	
	if(isStatic == false) return;

	int ii = 0;
	int spritesSize = sprites.size();
	for(int i = 0; i < spritesSize; i++)
	{
		if(ii==index)
		{
			curSprite = i;
		}
		ii++;
	}
	
}

void Animation::GenerateAuto(Texture* texture, int spriteWidth, int spriteHeight, 
				  int numColumn, int fromIndex, int toIndex, float renderTime)
{
	GenerateAuto(texture, 0, 0, spriteWidth, spriteHeight, numColumn, fromIndex, toIndex, renderTime);
}

void Animation::GenerateAuto(Texture* texture, int xBegin, int yBegin, int spriteWidth, int spriteHeight, 
				  int numColumn, int fromIndex, int toIndex, float renderTime)
{
	Sprite* sprite;
	for(int i = fromIndex; i<=toIndex; i++)
	{
		sprite = new Sprite((i%numColumn)*spriteWidth + xBegin, 
			(i/numColumn)*spriteHeight + yBegin,
			spriteWidth, spriteHeight,texture, renderTime);
		AddSprite(sprite);
	}
}

Animation::~Animation()
{
	int spriteSize = sprites.size();
	for(int i = 0; i < spriteSize; i++)
	{
		DELETE_SAFELY(sprites[i]);
	}
	sprites.clear();
}

void Animation::Render(int x, int y, float deep)
{
	sprites[curSprite]->Render(x, y, deep);
}
void Animation::Render(int x, int y, float alpha, float deep)
{
	sprites[curSprite]->Render(x, y, alpha, deep);
}
void Animation::Render(int x, int y, float xScale, float yScale, float angle, float alpha,float deep)
{
	sprites[curSprite]->Render(x, y, xScale, yScale, angle, alpha, deep);
}